<template>
  <div>
    <!-- 头部标题栏 -->
    <van-nav-bar fixed>
      <template #left>
        <img class="logo" :src="imgUrl">
      </template>
      <template #right>
        <van-icon name="search" size="18" color="#fff" @click.native="moveSearchPage"/>
      </template>
    </van-nav-bar>

    <!-- 标签栏 -->
    <div class="main">
      <van-tabs v-model="channelId" animated sticky offset-top="1.2267rem" @change="onClick">
      <!-- 绑定name的值为channle的id，方便后续点击 -->
        <van-tab
        v-for="channel in userChannelList"
        :key="channel.id"
        :title="channel.name"
        :name="channel.id"
        >
          <!-- 文章列表 -->
          <!-- 点击标签切换后，文章列表组件并不是被销毁了，而是被平移出视窗 -->
          <ArticlesList :cid="channelId"></ArticlesList>
        </van-tab>
          <!-- 编辑标签 -->
      </van-tabs>
      <van-icon name="plus" class="moreChannels" size="14px" @click="setChannelEdit(true)"></van-icon>
    </div>
    <!-- 频道管理 -->
    <van-popup v-model="channelEdit">
        <ArticlesChannelEdit :userChannelList="userChannelList" :moreChannelList="moreChannelList"/>
    </van-popup>

  </div>
</template>

<script>
import logoPng from '@/assets/images/logo.png'
import { addChangeListAPI, getUserchannelsAPI, updateChannelAPI } from '@/api/index'
import ArticlesList from './components/ArticlesList.vue'
import ArticlesChannelEdit from './components/ArticlesChannelEdit.vue'
import Mixin from '@/utils/mixin'
export default {
  name: 'Home',
  components: { ArticlesList, ArticlesChannelEdit },
  mixins: [Mixin],
  data () {
    return {
      imgUrl: logoPng,
      channelId: 0, // tab导航，激活的频道id（默认频道id为0）
      userChannelList: [], // 用户订阅的频道
      allChannelList: [], // 所有频道
      channelsSrcoll: {} // 不同频道的滚动位置
    }
  },
  computed: {
    // 更多频道
    moreChannelList () {
      // 过滤掉用户已经订阅的频道
      return this.allChannelList.filter((allItem) => {
        const index = this.userChannelList.findIndex(userItem => {
          return userItem.id === allItem.id
        })
        // 用户未订阅
        if (index === -1) {
          return true
        }
      })
    }
  },
  methods: {
    // =================文章==================
    // 切换标签，文章列表更新
    onClick (name) {
      this.channelId = name
      this.$nextTick(() => {
        // 恢复到原来滚动的位置
        // console.log('当前频道滚动：', this.channelsSrcoll[this.channelId])
        document.documentElement.scrollTop = this.channelsSrcoll[this.channelId]
      })
    },
    // =================频道==================
    // 获取所有的频道列表信息
    async getChannelInfo () {
      const res = await addChangeListAPI()
      this.allChannelList = res.data.data.channels
    },
    // 获取用户订阅的频道信息
    async getUserChannelsInfo () {
      const res = await getUserchannelsAPI({})
      this.userChannelList = res.data.data.channels
    },
    // 用户添加订阅频道
    async addChannel (channel) {
      // 更新本地页面的数据
      this.userChannelList.push(channel)
      // 同时发送请求更新后台数据
      this.updateChannelList()
    },

    // 用户删除订阅的频道
    async deleteChannel (channel) {
      const index = this.userChannelList.findIndex((item) => {
        return item.id === channel.id
      })
      // 删除频道
      this.userChannelList.splice(index, 1)
      this.updateChannelList()
    },
    // 更新后台数据
    async updateChannelList () {
      updateChannelAPI({ channels: this.userChannelList })
    },
    // 进入频道
    enterChannel (channelId) {
      // 关闭频道管理弹出层
      this.setChannelEdit(false)
      // 切换tab导航栏到相应频道
      this.channelId = channelId
    },
    // =================搜索===================
    moveSearchPage () {
      this.$router.push({
        path: '/search'
      })
    },
    // 保存滚动条位置
    scrollChange () {
      // 保存首页页面的滚动位置
      this.$route.meta.scrollT = document.documentElement.scrollTop
      // 保存频道的滚动位置
      this.channelsSrcoll[this.channelId] = document.documentElement.scrollTop
    }
  },
  created () {
    this.getUserChannelsInfo()
    this.getChannelInfo()
  },
  activated () {
    // 监听滚动，保存相应的滚动位置
    document.documentElement.scrollTop = this.$route.meta.scrollT
    window.addEventListener('scroll', this.scrollChange)
  },
  deactivated () {
    // 移除监听
    window.removeEventListener('scroll', this.scrollChange)
  },
  mounted () {
    this.$bus.$on('addChannel', this.addChannel)
    this.$bus.$on('deleteChannels', this.deleteChannel)
    this.$bus.$on('enterChannel', this.enterChannel)
  },
  beforeDestroy () {
    this.$bus.$off(['addChannel', 'deleteChannels', 'enterChannel'])
  }
}
</script>

<style lang='less' scoped>
.van-nav-bar {
  /deep/ &__content {
    .van-nav-bar__right {
      padding-right: 30px;
    }
  }
 .logo {
   width: 100px;
   height: 30px;
 }
}

.main {
  margin-top: 46px;
}
// 设置 tabs 容器的样式
/deep/ .van-tabs__wrap {
  padding-right: 30px;
  background-color: #fff;
}

.moreChannels {
  position: fixed;
  top: 60px;
  right: 8px;
  z-index: 99;
}
 .wrapper {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }

  .block {
    width: 100%;
    height: 100%;
    background-color: #fff;
  }
  .van-overlay {
    background-color: #fff;
  }
</style>
